package com.lby.graduation.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lby.graduation.entity.Post;
import com.lby.graduation.service.PostService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 李兵耀
 * @since 2020-12-29
 */
@RestController
@RequestMapping("/post")
public class PostController {
    @Resource
    private PostService postService;

    /*查询所有求购信息*/
    @GetMapping("/selectPost")
    public List<Post> selectPost() {
        return postService.selectPost();
    }

    /*mybatisPlus分页查询*/
    @GetMapping("/selectPagePost")
    public Map selectPagePost(Integer current, Integer size) {
        Page<Post> page = new Page<Post>(current, size);
        HashMap<String, Object> map = new HashMap<>();
        List<Post> post = postService.selectPagePost(page);
        long total = page.getTotal();
        map.put("post", post);
        map.put("code", 200);
        map.put("msg", "查找成功");
        map.put("count", total);
        return map;
    }

    /*根据userId查询求购信息*/
    @GetMapping("/selectUserPost")
    public List<Post> selectUserPost(Integer userId) {
        return postService.selectUserPost(userId);
    }

    /*根据postId查询求购信息*/
    @GetMapping("/selectPostByPostId")
    public Post selectPostByPostId(Integer postId) {
        return postService.selectPostByPostId(postId);
    }

    /*发布求购*/
    @GetMapping("/insert")
    public boolean insert(Post post) {
        return postService.save(post);
    }

    /*根据postId更新求购信息*/
    @GetMapping("/update")
    public boolean update(Post post) {
        return postService.updateById(post);
    }

    /*单个删除*/
    @PostMapping("/deletes")
    public boolean deletes(Integer id) {
        return postService.removeById(id);
    }

    /*admin后台*/
    /*批量删除*/
    @RequestMapping("/deletePosts")
    public Map deletePosts(String ids) {
        HashMap<String, Object> map = new HashMap<>();
        JSONArray array = JSON.parseArray(ids);//传过来的json字符串转换成json数组
        List<Integer> idList = new ArrayList<>();
        for (int i = 0; i < array.size(); i++)//遍历将取出的值存到集合
        {
            String str = array.get(i).toString();
            idList.add(Integer.valueOf(str));
        }
        boolean b = postService.removeByIds(idList);
        if (b = true) {
            map.put("code", 200);
            map.put("msg", "删除成功");
            map.put("idList",idList);
        } else {
            map.put("msg", "删除失败");
        }
        return map;
    }

}
